<?php

include_once 'common.php';

$filter = "WHERE status > -1";
if ($payload && count($payload) > 0) {
  foreach ($payload as $item) {
    if (is_array($item->value)) {
      if (count($item->value) > 0) {
        $str = " ' " . implode(" ',' ", $item->value) . " ' ";
        $filter .= " AND " . $item->key . " IN '(" . $str . "')";
      }
    } elseif (is_object($item->value)) {
      if ($item->value->value != '' && $item->value->value != 0) {
        $filter .= " AND " . $item->key . " " . $item->value->symbol . " '" . $item->value->value . "'";
      }
    } else {
      if ($item->value != '') {
        $filter .= " AND " . $item->key . " = '" . $item->value . "'";
      }
    }
  }
}

$sql = "SELECT * FROM `trex_records` {$filter} ORDER BY `trainingDate` DESC, `title` DESC";

$result = exec_sql($sql);
if ($result && gettype($result) == 'array' && count($result) > 0) {
  foreach ($result as $key => $value) {
    $result[$key]['subjects'] = json_decode($result[$key]['subjects']);
    $result[$key]['traineeLicences'] = json_decode($result[$key]['traineeLicences']);
    $result[$key]['subjectsComments'] = json_decode($result[$key]['subjectsComments']);
    $result[$key]['failedSubjects'] = json_decode($result[$key]['failedSubjects']);
    $result[$key]['evaluations'] = json_decode($result[$key]['evaluations']);
    $result[$key]['history'] = json_decode($result[$key]['history']);
  }
  output($result);
} else {
  output([]);
}
